/*
 * @Author: xiawei 1243162387@qq.com
 * @Date: 2024-03-28 16:26:44
 * @LastEditors: xiawei 1243162387@qq.com
 * @LastEditTime: 2024-04-15 18:53:00
 */
import inquirer from'inquirer';
import {execa} from 'execa';
import detect from 'detect-port';
import {config} from './config.js'

// 已占用端口列表
const occupiedList = [];

const checkPorts = Object.keys(config).map((key) => new Promise((resolve) => {
  detect(config[key].port).then((port) => {
    resolve({
      package: key,
      isOccupied: port !== config[key].port,
      port: config[key].port,
    });
  });
}));
// 运行选择命令
function runInquirerCommand() {
  inquirer
    .prompt([
      {
        name: 'devPackage',
        type: 'list',
        message: '请选择要启动的子应用',
        choices: Object.keys(config).filter((item) => item !== 'base-app').map((key) => {
          const { packageName, port, name_cn } = config[key];
          return {
            name: `${name_cn}(${packageName}:${port})`,
            value: key,
            disabled: occupiedList.find((item) => item.package === key).isOccupied ? '已启动' : false,
          };
        }),
      },
    ])
    .then(async (answers) => {
      execa('npm', ['run', 'dev', '-- --port', config[answers.devPackage].port], {
        cwd: `./apps/${answers.devPackage}`,
        stdio: 'inherit',
      });
    });
}

const appStart = async (service)=>{
 execa('npm', ['run', 'dev', '--port =', service.port], {
    cwd: './apps/base-app',
    stdio: 'inherit',
  });
}
Promise.all(checkPorts).then((ports) => {
  occupiedList.push(...ports);
  if (ports[0].isOccupied) {
    runInquirerCommand();
  } else {
    appStart(ports[0])
  }
});